// pages/Tabbar/My/My.js
//获取应用实例
const app = getApp();
const assetsAddress = app.globalData.global.assetsIp + '/' + app.globalData.global.assetsName;
import { getUser , updateUser , getUserAccount , getUserTeamNumber } from '../../../api/user';
import { getGradeConfig , queryAppInforMation } from '../../../api/brand';
import { getGoodsCollection } from '../../../api/goods';
import { getAwardRecordSum } from '../../../api/earning';
import { getGoodsStatusStatistics } from '../../../api/order';
import { ACCESS_TOKEN } from '../../../utils/types';
const regeneratorRuntime = require('../../../common/runtime');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    shareTitle: app.globalData.global.shareTitle,
    assetsAddress: assetsAddress,
    ip: app.globalData.global.http,
    gradeList: [], // 等级列表
    user: {},
    userColGoodsSum: 0, // 收藏数量
    userSonSum: 0, // 团队数量
    intrgral: 0, // 积分数量
    totalSum: 0, // 累计收益
    appList: [
      { label: '优惠券' , icon: `${assetsAddress}/my/couponIcon.png`, path: '/pages/Users/Coupons/Coupons'},
      // { label: '排行榜' , icon: `${assetsAddress}/my/rankingIcon.png`, path: '/pages/Systems/Rankings/Rankings'},
      { label: '售后规则' , icon: `${assetsAddress}/my/shhgzIcon.png`, path: '/pages/Users/Coupons/Coupons', isLink: true},
      { label: '积分任务' , icon: `${assetsAddress}/my/taskIntegratingIcon.png`, path: '/pages/Earnings/Integral/Integral'},
      { label: '邀请好友' , icon: `${assetsAddress}/my/shareIcon.png`, path: '/pages/Systems/Shares/Shares'},
      { label: '收货地址' , icon: `${assetsAddress}/my/addressIcon.png`, path: '/pages/Users/MyAddress/MyAddress'},
      { label: '新手引导' , icon: `${assetsAddress}/my/guldeNoviceIcon.png`, path: '/pages/Systems/GuideNovice/GuideNovice'},
      { label: '投诉建议' , icon: `${assetsAddress}/my/suggestionIcon.png`, path: '/pages/Systems/Feedbacks/Feedbacks'},
      { label: '公司介绍' , icon: `${assetsAddress}/my/introductionCompanyIcon.png`, path: '/pages/Systems/CompanyIntroduction/CompanyIntroduction'},
      { label: '直营加盟（免加盟费）' , icon: `${assetsAddress}/my/joinInvestmentIcon.png`, path: '/pages/Systems/JoinInvestment/JoinInvestment',},
      { label: '设置' , icon: `${assetsAddress}/my/settingIcon.png`, path: '/pages/Systems/Setting/Setting'},
      { label: '骑手工具' , icon: `${assetsAddress}/my/toolIcon.png`, path: '/pages/Riders/RidersLogin/RidersLogin',},
      { label: '员工系统' , icon: `${assetsAddress}/my/ygxtIcon.png`, path: '/pages/Systems/EmployeeSystem/EmployeeSystem', noBorder: true},
    ], // 应用专区数据
    pendingPayment: 0, // 待付款数量
    pendingDeliverGoods: 0, // 待发货数量
    pendingReceiving: 0, // 待收货数量
    pendingEvaluate: 0, // 待评价数量
    showPrivacyAuthor: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // wx.setStorageSync('access_token', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsicmVzMSJdLCJleHAiOjE2ODExMTAzNjEsInVzZXJfbmFtZSI6IntcImJyYW5kSWRcIjpcIjFcIixcInBhc3N3b3JkXCI6XCJcIixcInVzZXJJZFwiOlwiMTAwMDExXCJ9IiwianRpIjoiYmI4N2E4MDMtNDgwMC00OWRkLWIxZWEtMWNjOGMyZjI1NzkyIiwiY2xpZW50X2lkIjoie1wiYnJhbmRJZFwiOlwiMVwifSIsInNjb3BlIjpbIlJPTEVfV0VCIl19.T397kMVctk3C3DPt0RNVwZ24tIO3GAu5HZOx8oeosPw')
    var _this = this;
    // 实例化API核心类
    _this.getUser();
    _this._getGradeConfig();
    _this._getUserSonStat();
    _this._getIntegral();
    _this._getTotalSum();
    if (wx.onNeedPrivacyAuthorization){
      wx.onNeedPrivacyAuthorization((resolve) => {
        console.log('触发弹窗')
        // 触发弹窗
        _this.setData({
          showPrivacyAuthor: true,
        })
        _this.resolvePrivacyAuthorization = resolve
        console.log(resolve,resolve);
      })
    }  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if(wx.getStorageSync('hasUpdateUser') == '1'){
      this.getUser();
      wx.setStorageSync('hasUpdateUser','')
    }
    this._getGoodsStatusStatistics();
    this._getGoodsCollection();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getUser();
    this._getGradeConfig();
    this._getGoodsCollection();
    this._getUserSonStat();
    this._getIntegral();
    this._getTotalSum();
    setTimeout(()=>{
      wx.stopPullDownRefresh({
        success: (res) => {
          console.log(res,'刷新成功')
          wx.showToast({
            title: '刷新成功',
            icon: 'none',
          })
        },
      })
    },1000)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let userId = wx.getStorageSync('userId')
    return {
      title: this.data.shareTitle,
      path: '/pages/Welcome/Welcome?scene='+userId,
    }
  },
  // 页面跳转
  goNext(e){
    let _this = this;
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    if(item.isLink){
      queryAppInforMation({infoType: '2',title: item.label,page: _this.data.page})
      .then(res => {
        if(res.success){
          if(res.data.content.length > 0){
            var itm = res.data.content[0];
            if(res.data.content[0].imgUrl){
              wx.navigateTo({
                url: `/pages/Link/LinkImg/LinkImg?url=${encodeURIComponent(itm.imgUrl)}&title=${JSON.stringify(item.label)}`,
              })
            }else if(res.data.content[0].content){
              wx.navigateTo({
                url: `/pages/Link/LinkText/LinkText?content=${JSON.stringify(item.content)}&title=${JSON.stringify(item.label)}`,
              })
            }
          }
        }else{
          wx.showToast({
            title: res.errMessage,
            icon: 'none',
          })
        }
      })
    }else{
      wx.navigateTo({
        url: `${item.path}`,
      })
    }
  },
  // 获取用户个人信息
  getUser(){
    let _this = this;
    getUser()
    .then(res => {
      if(res.success){
        _this.setData({
          user: res.data,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取用户微信信息
  changeUserInfo(){
    let _this = this;
    wx.showModal({
      title: '温馨提示',
      content: '是否授权展示用户微信头像和昵称？',
      success: (bool) => {
        if(bool.confirm){
          wx.getUserProfile({
            desc: '展示头像和昵称',
            success: async(res) => {
              console.log(res,'res')
              try {
                await _this.setUserNickName(res.userInfo);
              } catch (error) {
                wx.showToast({
                  title: error,
                  icon: 'none',
                })
              }
              _this.setUserHeadImg(res.userInfo.avatarUrl);
            }
          })
        }
      }
    })
  },
  // 设置用户头像
  changeUserInfoAvatarUrl(e){
    console.log(e,'e')
    this.setUserHeadImg(e.detail)
  },
  setUserHeadImg(imgUrl){
    let _this = this
    var token = wx.getStorageSync(ACCESS_TOKEN)
    wx.getImageInfo({
      src: imgUrl,
      success: function(res){
        console.log(res,'res')
        wx.uploadFile({
          url: _this.data.ip + '/app/upload/user/headimg',
          filePath: res.path,
          name: 'headimg',
          formData: {
            'access_token': token,
          },
          success: function(res){
            console.log(res,'上传图片res')
            // if(res.success){
            // }
            _this.getUser();
          },
          fail: function(err){
            console.log(err)
          },
        })
      }
    })
  },
  // 设置用户昵称
  changeUserInfoNickname(e){
    this.setUserNickName(e.detail)
  },
  setUserNickName(nickName){
    let _this = this
    var params = {
      nickname: nickName,
    }
    // if(!_this.data.user.provnice){
    //   params.province = userInfo.province;
    //   params.city = userInfo.city;
    //   params.country = userInfo.country;
    // }
    return new Promise((resolve,reject) => {
      updateUser(params)
      .then(res=>{
        if(res.success){
          _this.getUser();
          resolve();
        }else{
          reject(res.errMessage)
        }
      })
    })
  },
  // 获取品牌等级配置信息
  _getGradeConfig(){
    let _this = this;
    getGradeConfig()
    .then(res => {
      if(res.success){
        _this.setData({
          gradeList: res.data.content
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取商品收藏信息
  _getGoodsCollection(){
    let _this = this;
    var storehouseId = wx.getStorageSync('storehouseId');
    // var areaId = wx.getStorageSync('areaId');
    getGoodsCollection({storehouseId:storehouseId,areaId: '0'})
    .then(res => {
      if(res.success){
        _this.setData({
          userColGoodsSum: res.data.totalElements,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取团队数量
  _getUserSonStat(){
    let _this = this;
    getUserTeamNumber()
    .then(res => {
      if(res.success){
        _this.setData({
          userSonSum: res.data.totalCount,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取积分数量
  _getIntegral(){
    let _this = this;
    getUserAccount(5)
    .then(res => {
      if(res.success){
        _this.setData({
          intrgral: res.data.balance,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取累计收益信息
  _getTotalSum(){
    let _this = this;
    getAwardRecordSum({status: '1'})
    .then(res => {
      if(res.success){
        _this.setData({
          totalSum: res.data,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取订单角标信息
  _getGoodsStatusStatistics(){
    let _this = this;
    getGoodsStatusStatistics()
    .then(res => {
      if(res.success){
        _this.setData({
          pendingPayment : res.data['pendingPayment'],
          pendingDeliverGoods : res.data['pendingDeliverGoods'],
          pendingReceiving : res.data['pendingReceiving'],
          pendingEvaluate : res.data['pendingEvaluate'],
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  handleAgreePrivacyAuthorizationFun(){
    console.log('同意之后的回调');
  },
})